/* Copyright © 2010 LPRM
Universidade Federal do Espírito Santo - RNP-GT CWTools

This file is part of GW-Android.

GW-Android is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

GW-Android is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with GW-Android. If not, see <http://www.gnu.org/licenses/>. */
package br.ufes.cwtools.android.components.map;

import java.io.InputStream;
import java.util.LinkedList;
import java.util.List;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import android.util.Log;

public class GeoObjectsParser {
	private GeoObjectsParser() {
		/* Prevents instantiation. */
	}
	
	public static List<GeoObject> parse(InputStream source) {
		try {
			SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
			GeoObjectsHandler handler = new GeoObjectsHandler();
			parser.parse(source, handler);
			return handler.getGeoObjects();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} 
	}
}

class GeoObjectsHandler extends DefaultHandler {
	private static final String TAG = "XmlParser";

	private static final String GEO_OBJECT = "GeoObject";
	
	private List<GeoObject> geoObjects = null;
	
	public List<GeoObject> getGeoObjects() {
		return this.geoObjects;
	}
	
	@Override
	public void startDocument() throws SAXException {
		super.startDocument();
		this.geoObjects = new LinkedList<GeoObject>();
	}
	
	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		super.startElement(uri, localName, qName, attributes);
		
		if (localName.equalsIgnoreCase(GEO_OBJECT)) {
			try {
				double lat = Double.parseDouble(attributes.getValue("lat"));
				double lon = Double.parseDouble(attributes.getValue("lon"));
				String label = attributes.getValue("label");
				String reference = attributes.getValue("reference");
				String type = attributes.getValue("type");
				this.geoObjects.add(new GeoObject(lat, lon, label, reference, type));
			} catch (NumberFormatException e) {
				Log.d(TAG, "Invalid or missing latitude/longitude attibute on element" + GEO_OBJECT + ".");
			}
		}
	}
}